#include "Arduino.h"
#include "soundremote.h"
#include "tvremote.h"

SoundRemote soundRemote;
TVRemote tvRemote;

// Pin 13 has an LED connected on most Arduino boards.
// give it a name:
int led = 13;

// the setup routine runs once when you press reset:
void setup() {
  Serial.begin(9600);
  // initialize the digital pin as an output.
  pinMode(led, OUTPUT);
}

double Thermister(int RawADC) {
  double Temp;
  // See http://en.wikipedia.org/wiki/Thermistor for explanation of formula
  Temp = log(((10240000/RawADC) - 10000));
  Temp = 1 / (0.001129148 + (0.000234125 * Temp) + (0.0000000876741 * Temp * Temp * Temp));
  Temp = Temp - 273.15;           // Convert Kelvin to Celcius
  return Temp;
}

void loop() {
  if(Serial.available() > 1) {
    byte device = Serial.read();
    byte code = Serial.read();

    if(device == 'a') {
        if(code == 'a') {
            digitalWrite(led, HIGH);
        }
        else {
            digitalWrite(led, LOW);
        }
    }
    else if (device == 't') {
        double temp = Thermister(analogRead(0));
        Serial.println(temp);
        Serial.flush();
    }
    else if(device == 's') {
      //for now use a-z as codes
      code -= 97;
      if(code < 7) {
          soundRemote.sendCode(SoundCode(code));
      }
      else {
          Serial.print("ERROR: no code ");
          Serial.print(code);
          Serial.print(" on sound remote\n");
          Serial.flush();
      }
    }
    else if(device == 'v') {
        tvRemote.sendCode(TVCode(code));
    }
  }
}
